import mRouter from '@/common/router';
import mRoutesConfig from '@/config/routes.config.js'
import mConstDataConfig from '@/config/constData.config';
import mStore from '@/store';
import config from '@/config/config.js'
import $mRoutesConfig from '@/config/routes.config.js';
import urlEncode from '@/common/urlEncode.js'
import md5 from '@/common/md5.js'
// import ksort from 'ksort';
//常用方法集合
export default {
	
	
	
	/**
	 * 获取节点信息的对象
	 * @param {Object} selector 个匹配选择器 selector
	 */
	getRect(selector){
			return new Promise((resolve) => {
				let view = uni.createSelectorQuery().select(selector);
				view.fields({
					size: true,
					rect: true,
					scrollOffset:true
				}, (res) => {
					resolve(res);
				}).exec();
			})
	},
	
	
	
	
	/**
	 * 保存图片
	 */
	savePoster() {
		let _self = this;
		// #ifndef MP-WEIXIN
		_self.saveImgToLocal();
		// #endif
		// #ifdef MP-WEIXIN
	
		//获取相册授权
		uni.getSetting({
			success(res) {
				console.log('授权', res)
				if (!res.authSetting['scope.writePhotosAlbum']) {
					uni.authorize({
						scope: 'scope.writePhotosAlbum',
						success() {
							//这里是用户同意授权后的回调
							_self.saveImgToLocal();
						},
						fail() { //这里是用户拒绝授权后的回调
							uni.showModal({
								title: "是否授权相册使用权限",
								content: "需要打开您的相册，请确认授权，否则保存海报功能无法使用",
								success: (tip) => {
									if (tip.confirm) {
										// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
										uni.openSetting({
											success: (data) => {
												// 如果用户授权了地理信息在，则提示授权成功
												if (data
													.authSetting[
														'scope.writePhotosAlbum'
													] === true
												) {
													uni.showToast({
														title: "授权成功",
														icon: "success",
														duration: 1000
													})
													_self.saveImgToLocal();
	
												} else {
													uni.showToast({
														title: "授权失败",
														icon: "none",
														duration: 1000
													})
												}
											}
										})
									}
								},
							});
	
						}
					})
				} else { //用户已经授权过了
					// console.log('保存还白！！', res)
					_self.saveImgToLocal();
				}
			},
			fail(res) {
				uni.showToast({
					title: "调用授权窗口失败",
					icon: "none",
					duration: 1000
				})
			}
		})
	
	
		// #endif
	
	},
	/**
	 * 保存图片到本地
	 * @param {Object} e
	 */
	saveImgToLocal(e) {
		let _self = this;
		
		uni.downloadFile({
			url: _self.poster, //图片地址
			success: (res) => {
				// console.log('')
				if (res.statusCode === 200) {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function() {
							uni.showToast({
								title: "保存成功",
								icon: "success",
								duration: 1500,
							});
							_self.$refs.popup.close('center');
						},
						fail: function() {
							uni.showToast({
								title: "保存失败",
								icon: "none"
							});
						}
					});
				}
			}
		});
		
	
	},
	
	/**
	 * 返回绑定手机号
	 */
	backToBindPhone(){
		let url = mRoutesConfig.login.path;
		url += '?bind_phone=1';
		this.backToLogin(url,false)
		// this.navTo(url);
		
		
	},
	
	/**
	 * 检查是否绑定手机号
	 */
	checkBindPhone(){
		let _this = this;
		//先检查登录
		if(!mStore.getters.hasLogin){
			uni.showModal({
			    content: '您还未登录，是否前往登录？',
			    success: (confirmRes) => {
			        if (confirmRes.confirm) {
					   this.backToLogin();
			        }
			    }
			});
			return false;
		}
		//已登录，检查是否绑定手机号
		let memberInfo = mStore.state.userInfo;
		if(memberInfo && !memberInfo.know_phone){
			uni.showModal({
				title:'温馨提示',
				content:'您还未绑定手机号，请前往绑定',
				confirmText:'前往绑定',
				cancelText:'暂不',
				success(result) {
					if(result.confirm){
						_this.backToBindPhone();
						
					}else{
						_this.jump();
					}
				}
			})
			
			return false;
		}
		return true;
		
	},
	
	/**
	 * 返回之前的页面
	 */
	backToPrePage(){
		let _this = this;
		const backToPage = _this.getBackPage();
		if (backToPage) {
			let backUrl = JSON.parse(backToPage).route || '';
			if (_this.checkTabBarUrl(backUrl)) {
				uni.reLaunch(JSON.parse(backToPage));
			} else {
		
				uni.redirectTo(JSON.parse(backToPage));
			}
			_this.removeBackPageStorage();
			// await _this.$mStore.commit('removeBackPage');
			// await _this.$mStore.commit('removeWechatUserInfo');
		} else {
			
			//返回前一页
			uni.navigateBack({
				delta:1
			})
		}
		
	},
	
	
	
	/**
	 * 检查是否会员
	 */
	checkVip(){
			let memberInfo = mStore.state.userInfo || {}; //用户信息;
			let _this = this;
			if(memberInfo.vip_int === 2){
				//是会员
				return true;
			}else{
				uni.showModal({
					content:'您还未开通会员，前往开通',
					confirmText:'前往开通',
					cancelText:'暂不',
					success(res) {
						if(res.confirm){
							_this.backToLogin('',false);
							
						}
					}
				})
				
			}
			return false;
		
	},
	
	
	//预览图片
	previewImg(i, imgs,callback) {
		uni.previewImage({
			current:i,
			urls: imgs,
			// #ifdef APP-PLUS
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏'],
				success: function(data) {
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			},
			
			// #endif
			success: function(res){
				callback(res);
			}
		});
	},
	
	//单张图片上传
	uploadImg(callback) {
	    uni.chooseImage({
	        count: 1,
	        sizeType: ['original', 'compressed'],
	        sourceType: ['album', 'camera'],
	        success(res) {
	            console.log('文件上传！',res)
	            callback(res.tempFilePaths[0]);
	        }
	    })
	},
	//选择多图图片
	uploadMultiImg(num, callback) {
	    uni.chooseImage({
	        count: num,
	        sizeType: ['original', 'compressed'],
	        sourceType: ['album', 'camera'],
	        success(res) {
	            // console.log(res)
	            callback(res.tempFilePaths);
	            // tempFilePath可以作为img标签的src属性显示图片
	        }
	    })
	},
	
	//单个视频上传
	uploadVideo(callback) {
	    uni.chooseVideo({
	        count: 1,
	        sourceType: ['album', 'camera'],
	        success(res) {
	            // console.log(res)
	            callback(res.tempFilePaths[0]);
	        }
	    })
	},
	//选择多个视频
	uploadVideos(num, callback) {
	    uni.chooseVideo({
	        count: num,
	        sourceType: ['album', 'camera'],
	        success(res) {
	            // console.log(res)
	            callback(res.tempFilePaths);
	            // tempFilePath可以作为img标签的src属性显示图片
	        }
	    })
	},
	
	
	/**
	 * 调起扫一扫
	 * 
	 * scanType  二维码是'qrCode'，一维码是'barCode'，
	 * onlyFromCamera 是否只能从相机扫码，不允许从相册选择图片
	 */
	
	scanCode(scanType = ['qrCode','barCode','WX_CODR'],onlyFromCamera = true,sucFunc,failFunc,price){
		
		// #ifdef MP-WEIXIN
		console.log('微信扫码')
		wx.scanCode({
		    // scanType: scanType,
			// onlyFromCamera:onlyFromCamera,
		    success: function (res) {
		        console.log('返回内容：' + res);
				if(sucFunc) sucFunc(res,price);
				
		    },
			fail(err) {
				console.log('扫码失败',err)
				if(failFunc) failFunc();
			}
		});
		// #endif
		
		// #ifndef MP-WEIXIN
		uni.scanCode({
		    scanType: scanType,
			onlyFromCamera:onlyFromCamera,
		    success: function (res) {
		        console.log('返回内容：' + res);
				if(sucFunc) sucFunc(res,price);
				
		    },
			fail() {
				if(failFunc) failFunc();
			}
		});
		// #endif
	},
	
	/**
	 * 金额小数限制(保留两位小数)
	 */
	priceLimit(number){
		return number.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
		
	},
	
	
	/**
	 * 拿上一页的url
	 */
	getBackPage(){
		let backToPage = uni.getStorageSync('backToPage');
		return backToPage;
	},
	setBackPageStorage(data){
		console.log('设置缓存',data)
		 uni.setStorageSync('backToPage',data);
	},
	removeBackPageStorage(){
		 uni.removeStorageSync('backToPage');
	},
	/**
	 * 检测url是否为tabbar页面
	 */
	checkTabBarUrl(url){
		if(!url) return false;
		
		let tabBarUrls = ['/pages/index/index','/pages/jyclass/list',"/pages/live/list","/pages/user/user"];
		if(tabBarUrls.indexOf(url) > -1){
			return true;
		}
		return false;
	},
	
	/**
	 * 小数保留2位，非四舍五入
	 */
	floorNumber(number){
		return parseFloat(parseInt(number * 100)/100).toFixed(2);
		
	},
	/**
	 * 加减法运算(默认为加)
	 */
	addFloor(num1,num2,isadd=true){
		if(!isadd){
			let res = parseFloat(((num1 * 100) - (num2*100))/100);
			if(res < 0){
				res = 0;
			}
			res = res.toFixed(2);
			return res;
		}
		return parseFloat(((num1 * 100) +(num2*100))/100).toFixed(2);
	},
	
	
	
	
	/**
	 * 是否登录
	 */
	isLogin(){
		let hasLogin = mStore.getters.hasLogin;
		if(hasLogin){
			return true;
		}
		return false;
	},

	/**
	 * 通用跳转
	 * @param {Object} url
	 */
	navTo(url, type="push",data='',checkLogin = true) {
	
	    if (!url) {
	        return;
	    }
		let _this = this,
			jumpObj = {},
			hasLogin = mStore.getters.hasLogin
			
		jumpObj.route = url	
	    if (checkLogin && !hasLogin) {
			//uni.getStorageSync('backToPage','')
	        uni.showModal({
	            content: '您还未登录，是否前往登录？',
	            success: (confirmRes) => {
	                if (confirmRes.confirm) {
						/* console.log(mRoutesConfig.login.path)
						
	                   mRouter.push({route: mRoutesConfig.login.path}); */
					   this.backToLogin();
	                }
	            }
	        });
	    } else {
			if(data){
				jumpObj.query = data 
			}
			// console.log(jumpObj)
			switch(type){
				case 'push':
					 mRouter.push(jumpObj)
					break
				case 'switchTab':
					 mRouter.switchTab(jumpObj)
					break
				case 'redirectTo':
					 mRouter.redirectTo(jumpObj)
					break
				case 'reLaunch':
					 mRouter.reLaunch(jumpObj)
					break
			}
	       
	    }
	},
	
	/**
	 * 设置要返回的页面地址
	 */
	setBackToPage(data){
		//let data = {route:url,"query":query}
		uni.setStorageSync('backToPage', data)
	},
	/**
	 * set导航栏标题
	 */
	setNavBarTitle(title){
		uni.setNavigationBarTitle({
		            title:title,
		})
	},
	
	
	/**
	 * 模态框提示
	 */
	_modal(title,content='',showCancel=true){
		//if(!title)
		uni.showModal({
		    title: title,
		    content: content,
			showCancel:showCancel,
		   
		});
		
	},
	/**
	 * toast提示
	 */
	toast(title, duration = 2000, mask = false, icon = 'none') {
		if (Boolean(title) === false) {
			return;
		}
		uni.showToast({
			title,
			duration,
			mask,
			icon
		});
	},
	

	
	/**
	 * 跳转回缓存好的页面
	 */
	async backToOrigin(url='',index = 1) {
		// 存当前页面的地址
		const currentPage = getCurrentPages()[getCurrentPages().length - 1];
		const params = {};
		// #ifdef H5
		params.route = `/${currentPage.$vm.route}`;
		params.query = currentPage.$vm.$mp && currentPage.$vm.$mp.query;
		// #endif
		// #ifdef MP
		params.route = `/${currentPage.$vm.__route__}`;
		params.query = currentPage.$vm.$mp && currentPage.$vm.$mp.query;
		// #endif
		// #ifdef APP-PLUS
		params.route = `/${currentPage.route}`;
		params.query = currentPage.options;
		// #endif
		//添加缓存
		//console.log('上一页缓存：',params)
		await uni.setStorageSync('backToPage', JSON.stringify(params));
		
		if(url){ 
			// mRouter.push({route: url,query:{_index: index}});
			uni.navigateTo({
				url: url
			});
			
		}
		
	},
	
	
	
	/**
	 * 返回登录页面
	 */
	 async backToLogin(url='',isLogin=true) {
		// 存当前页面的地址
		const currentPage = getCurrentPages()[getCurrentPages().length - 1];
		const params = {};
		// #ifdef H5
		params.route = `/${currentPage.$vm.route}`;
		params.query = currentPage.$vm.$mp && currentPage.$vm.$mp.query;
		// #endif
		// #ifdef MP
		params.route = `/${currentPage.$vm.__route__}`;
		params.query = currentPage.$vm.$mp && currentPage.$vm.$mp.query;
		// #endif
		// #ifdef APP-PLUS
		params.route = `/${currentPage.route}`;
		params.query = currentPage.options;
		// #endif
		//添加缓存
		// console.log('上一页缓存：',params)
		// await uni.setStorageSync('backToPage', JSON.stringify(params));
		await this.setBackPageStorage(JSON.stringify(params));
		/* await uni.removeTabBarBadge({index: mConstDataConfig.cartIndex}); */
		if(isLogin){
			// console.log('准备跳转登录页')
			// await mStore.commit('logout');
			
			mRouter.redirectTo({route: $mRoutesConfig.login.path});
		}else{
			if(url){ 
				mRouter.push({route: url});
			}
		}
		
		// uni.showModal({
		// 	content: '会话已过期，是否跳转登录页面？',
		// 	success: (confirmRes) => {
		// 		if (confirmRes.confirm) {
		// 			mRouter.push({route: '/pages/public/logintype'});
		// 		}
		// 	}
		// });
	},
	/**
	 * 返回上一页携带参数
	 */
	prePage(index) {
		let pages = getCurrentPages();
		let prePage = pages[pages.length - (index || 2)];
		// #ifdef H5
		return prePage;
		// #endif
		return prePage.$vm;
	},
	
	/**
	 * 开发环境全局打印日志
	 * @param {Object} title
	 */
	log(title) {
		if (process.env.NODE_ENV === 'development' && Boolean(title) === true) {
			console.log(JSON.stringify(title));
		}
	},
	
	
	/**
	 * 获取一个随机数
	 * @param {Object} min
	 * @param {Object} max
	 */
	random(min, max) {
		switch (arguments.length) {
			case 1:
				return parseInt(Math.random() * min + 1, 10);
				break;
			case 2:
				return parseInt(Math.random() * (max - min + 1) + min, 10);
				break;
			default:
				return 0;
				break;
		}
	},
	
	
	
	/*
	 * obj 转 params字符串参数
	 * 例子：{a:1,b:2} => a=1&b=2
	 */
	objParseParam(obj) {
		let paramsStr = '';
		if (obj instanceof Array) return paramsStr;
		if (!(obj instanceof Object)) return paramsStr;
		for (let key in obj) {
			paramsStr += `${key}=${obj[key]}&`;
		}
		return paramsStr.substring(0, paramsStr.length - 1);
	},
	
	/*
	 * obj 转 路由地址带参数
	 * 例子：{a:1,b:2} => /pages/index/index?a=1&b=2
	 */
	objParseUrlAndParam(path, obj) {
		let url = path || '/';
		let paramsStr = '';
		if (obj instanceof Array) return url;
		if (!(obj instanceof Object)) return url;
		paramsStr = this.objParseParam(obj);
		paramsStr && (url += '?');
		url += paramsStr;
		return url;
	},
	
	/*
	 * 获取url字符串参数
	 */
	getRequestParameters(locationhref) {
		let href = locationhref || '';
		let theRequest = new Object();
		let str = href.split('?')[1];
		if (str != undefined) {
			let strs = str.split('&');
			for (let i = 0; i < strs.length; i++) {
				theRequest[strs[i].split('=')[0]] = (strs[i].split('=')[1]);
			}
		}
		return theRequest;
	},
	
	/**
	 * 加密字符串
	 */
	strEncode(str) {
		const key = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		let l = key.length;
		let a = key.split('');
		let s = '', b, b1, b2, b3;
		for (let i = 0; i < str.length; i++) {
			b = str.charCodeAt(i);
			b1 = b % l;
			b = (b - b1) / l;
			b2 = b % l;
			b = (b - b2) / l;
			b3 = b % l;
			s += a[b3] + a[b2] + a[b1];
		}
		return s;
	},
	
	/**
	 * 解密字符串
	 */
	strDecode(str) {
		const key = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		let l = key.length;
		let b, b1, b2, b3, d = 0, s;
		s = new Array(Math.floor(str.length / 3));
		b = s.length;
		for (let i = 0; i < b; i++) {
			b1 = key.indexOf(str.charAt(d));
			d++;
			b2 = key.indexOf(str.charAt(d));
			d++;
			b3 = key.indexOf(str.charAt(d));
			d++;
			s[i] = b1 * l * l + b2 * l + b3
		}
		b = eval('String.fromCharCode(' + s.join(',') + ')');
		return b;
	},
	
	

	/**
	 * 自定义格式化时间为刚刚，几分钟前，几小时前等
	 */
	formatDateDiff(dateTimeStamp,isStr=true){
		let result = '';
		if(isStr){
			//时间字符串格式
			dateTimeStamp = new Date(dateTimeStamp).getTime();
		}
		var minute = 1000 * 60;
		var hour = minute * 60;
		var day = hour * 24;
		var halfamonth = day * 15;
		var month = day * 30;
		var now = new Date().getTime();
		var diffValue = now - dateTimeStamp;
		
		if(diffValue < 0){
			return;
		}
		var monthC =diffValue/month;
		var weekC =diffValue/(7*day);
		var dayC =diffValue/day;
		var hourC =diffValue/hour;
		var minC =diffValue/minute;
		if(monthC>=1){
			result="7天前";
			// result="" + parseInt(monthC) + "月前";
		}
		else if(weekC>=1){
			result="7天前";
			// result="" + parseInt(weekC) + "周前";
		}
		else if(dayC>=1){
			if(dayC > 7){
				result="7天前";
			}else{	
				result="1天前";
			}
			// result=""+ parseInt(dayC) +"天前";
		}
		else if(hourC>=1){
			result="1小时前";
			// result=""+ parseInt(hourC) +"小时前";
		}
		else if(minC>=1){
			if(minC < 30){
				result = "刚刚"
			}else{
				result=""+ parseInt(minC) +"分钟前";
			}
			
			
		}
		return result;
	},
	
	/**
	 * 时间转化为几天前,几小时前，几分钟前,几周前
	 * @param {Object} dateTimeStamp
	 */
	getDateDiff(dateTimeStamp,isStr=false){
		let result = '';
		if(isStr){
			//时间字符串格式
			dateTimeStamp = new Date(dateTimeStamp).getTime();
		}
		var minute = 1000 * 60;
		var hour = minute * 60;
		var day = hour * 24;
		var halfamonth = day * 15;
		var month = day * 30;
		var now = new Date().getTime();
		var diffValue = now - dateTimeStamp;
		if(diffValue < 0){return;}
		var monthC =diffValue/month;
		var weekC =diffValue/(7*day);
		var dayC =diffValue/day;
		var hourC =diffValue/hour;
		var minC =diffValue/minute;
		if(monthC>=1){
			result="" + parseInt(monthC) + "月前";
		}
		else if(weekC>=1){
			result="" + parseInt(weekC) + "周前";
		}
		else if(dayC>=1){
			result=""+ parseInt(dayC) +"天前";
		}
		else if(hourC>=1){
			result=""+ parseInt(hourC) +"小时前";
		}
		else if(minC>=1){
			result=""+ parseInt(minC) +"分钟前";
		}else
		result="刚刚";
		return result;
	},
	
	
	/**
	 * 时间格式化显示
	 * @param {is_time} 是否显示完整时间。
	 */
	getTime:function(time,is_time = false){
		let date = '';
		if(time){
			date = new Date(time);
		}else{
			date = new Date();
		}
		let year = date.getFullYear(),
		month = date.getMonth() + 1,
		day = date.getDate();
		if(!is_time){
			var timer = year + '-' + month + '-' + day
			return timer;
		}
		let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
		minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
		second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		month >= 1 && month <= 9 ? (month = "0" + month) : "";
		day >= 0 && day <= 9 ? (day = "0" + day) : "";
		var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
		return timer;
	},
	
	
	checkPhone(phone){
		return /^1[0-9]{10}$/.test(phone);
	},

	/**
	 * 手机号隐藏部分数字为*
	 * @param {start} 隐藏的开始位置
	 * @param {length} 隐藏的长度
	 */
	hidePhone(phone,start=4, length=4){
		
		
		 var mphone = phone.substring(0, start-1) + '*'.repeat(length) + phone.substring(11-start);
		 return mphone;
	},
	
	
	hideIdCard(idCard){
		var idCard_str = idCard.substring(0, 6) + '*'.repeat(8) + idCard.substring(14);
		return idCard_str;
	},
	hideRealName(name){
		let length = name.length;
		var res = name.substring(0, 1) + '*'.repeat(length - 1);
		return res;
	},
	/**
	 * 隐藏姓，只显示最后一个名
	 */
	hideSurname(name){
		
		let length = name.length;
		var res =  '*'.repeat(length - 1) + name.substr(-1);
		return res;	
	},
	
	
	
	/**
	 * 生成唯一的随机字符串
	 * @param {Object} length
	 */
	genID(length=32){
		return Number(Math.random().toString().substr(3,length) + Date.now()).toString(36);
	},
	
	/**
	 * 唯一id
	 */
	guid() {
	    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
	        var r = Math.random() * 16 | 0,
	            v = c == 'x' ? r : (r & 0x3 | 0x8);
	        return v.toString(16);
	    });
	},
	
	
	
	//签名算法
	getSign(data = null){
		const timeStamp = Date.parse(new Date()) / 1000;
		const nounceStr = this.guid();
		
		const sn = 'test123';
		let urlStr = '';
		if(data == null){
			urlStr = 'timeStamp=' + timeStamp + '&nounceStr=' + nounceStr;
		}else{
			urlStr = urlEncode(data) + 'timeStamp=' + timeStamp + '&nounceStr=' + nounceStr;
		}
		
		let result = {};
		let sign = '';
		sign = md5(sn + md5(urlStr + sn));
		result['nounceStr'] = nounceStr;
		result['timeStamp'] = timeStamp;
		result['sign'] = sign ;
		
		return result;
	},
	
	
	

	/**
	 * 密码md5加密
	 */
	md5Password(password){
		if(!password)return false;
		return md5(password);
	},
	
	/**
	 * 设置系统剪贴板的内容
	 * @param {string} data 需要设置的内容
	 * @returns {Promise} 设置状态
	 */
	setClipboardData(data) {
		if(!data){
			return false;
		}
		return new Promise((success, fail) => {
			// #ifndef H5
			uni.setClipboardData({ data, success, fail });
			// #endif
	
			// #ifdef H5
			// navigator.clipboard.writeText(data).then(success).catch(fail);
			const textarea = document.createElement('textarea');
			textarea.value = data;
			textarea.readOnly = 'readOnly';
			document.body.appendChild(textarea);
			textarea.select();
			textarea.setSelectionRange(0, data.length);
			document.execCommand('copy');
			textarea.remove();
			success(data);
			// #endif
		});
	},
	
	/**
	 * 获取系统剪贴板内容
	 * @returns {Promise} 剪贴板内容
	 */
	getClipboardData() {
		return new Promise((success, fail) => {
			// #ifndef H5
			uni.getClipboardData({ success, fail });
			// #endif
	
			// #ifdef H5
			navigator.clipboard.readText().then(success).catch(fail);
			// #endif
		});
	},
	//获取设备号
	getDeviceId(phone = ''){
			
			let deviceId = uni.getStorageSync('sys_deviceId') || '';
			if(deviceId.length == 0)
			{
				let str = phone+Math.ceil(Math.random()*10000000);
				deviceId = md5(str);
				uni.setStorageSync('sys_deviceId', deviceId);
			}
			return deviceId;
	},
	
	/**
	 * 获取上一页的缓存信息
	 */
	getBackPage(){
		// 跳转到登录页之前的页面
		let  backToPage = uni.getStorageSync('backToPage');
		return backToPage;	
	},
	/**
	 * 清除上一页缓存
	 */
	removeBackPage(){
		uni.removeStorageSync('backToPage')
	},
	
	/**
	 * 前端过滤emoj
	 */
	filterEmoj(str){
		
		//\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]|\ud83d[\ude80-\udeff]
		let regStr = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]|\ud83d[\ude80-\udeff]/ig;
		
		
		if(regStr.test(str)){
		　　str = str.replace(regStr,"");
		}
		// console.log('emoj!',str,str =='')
		return str;
		
	},
	

	
}

